//
//  WBAuthViewController.swift
//  WB123
//
//  Created by xuyunde mac pro on 2017/7/1.
//  Copyright © 2017年 NSObjiect. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBAuthViewController: UIViewController {

    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.white
        setupNav()
    }
    // 关闭控制
    @objc private func cancelClick(){
        dismiss(animated: true, completion: nil)
    }
    
    // 自动填充
    @objc private func aotufillClick(){
        print("自动填充")
        // js字符串-----------------在页面选中文本框并修改值
        let jsString = "document.getElementById('userId').value='\(HMWBNAME)';document.getElementById('passwd').value='\(HMWBPASSWD)'"
        // js注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    //设置导航
    private func setupNav(){
        //设置title
        navigationItem.title = "微博登录"
        //左右侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: nil, title: "自动填充", target: self, action: #selector(aotufillClick))
    }
    // 懒加载控件
    // webView
    private lazy var webView: UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        // webView要跳转的URL,字符串拼接参数appkey 和 回调页
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(HMAPPKEY)&redirect_uri=\(HMREDIRECT_URI)"
        print(urlString)
        // 字符串得到url(把字符串转换为URL)
        let url = URL(string: urlString)
        // 判断url是否为nil,如果为nil返回个空页面就是webView,guard
        guard let u = url else{
            return webView
        }
        webView.loadRequest(URLRequest(url: u))
        return webView
    }()
}

extension WBAuthViewController: UIWebViewDelegate{
    
    // 开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //监听webView将要加载的request, 默认不实现true,也就是同意当前webView加载这个request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //通过request 得到对应的urlstring - >absouletstring 为的是拿到code
        let urlString = request.url?.absoluteString
        // 判断urlString 是否为nil 而且是否前缀为我们设置的回调页,则是含有code的url
        // 判断字符串的前缀hasPrefix 后缀hasSuffix
        if let u = urlString, u.hasPrefix(HMREDIRECT_URI) {
            // 获取地址的请求参数部分字符串query 判断是否为nil(y严谨)
            if let query = request.url?.query {
                print(query)
                // substring(from: "code=".endIndex) 从code=开始截取后面的,得到code
                let code = query.substring(from: "code=".endIndex)
                print("终于等到你code",code)
                
                WBOAuthViewModel.share.getUserAccount(code: code, finish: { (isFinish) in
                    // 如果为false 代表请求失败
                    if !isFinish{
                        print("请求失败")
                    }else{
                        print("请求成功")
                        // 关闭控制器
                        self.dismiss(animated: false, completion: { 
                            // 发送通知
                            NotificationCenter.default.post(name: HMSWITCHROOTVIEWCONTROLLERNOTI, object: nil)
                        })
                        
                    }
                })
                
            }
        }
        return true
    }
}
